package com.xiantm.study.thread.towparsetermination.jdk.cyclicbarrier;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class MyTask implements Runnable {

    private static final int PHASE = 5;
    private final CyclicBarrier phaseBarrier;
    private final CountDownLatch countDownLatch;
    private final int context;
    private static final Random random = new Random(314159);

    public MyTask(CyclicBarrier cyclicBarrier, CountDownLatch countDownLatch, int context){
        this.phaseBarrier = cyclicBarrier;
        this.countDownLatch = countDownLatch;
        this.context = context;
    }


    @Override
    public void run() {
        try{
            for (int phase = 0; phase < PHASE; phase++) {
                doPhase(phase);
                phaseBarrier.await();
            }
        }
        catch (InterruptedException | BrokenBarrierException e)
        { e.printStackTrace();}
        finally {
            countDownLatch.countDown();
        }
    }

    private void doPhase(int phase){
        String name = Thread.currentThread().getName();
        System.out.println(name + ":MyTask:BEGIN:context = " + context + ", phase = " + phase);
        try {
            Thread.sleep(random.nextInt(3000));
        }catch (InterruptedException ignored){}finally {
            System.out.println(name+":MyTask:END:context = " + context + ", phase = " + phase);
        }
    }
}
